<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Basic DataGrid - jQuery EasyUI Demo</title>
	<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
	<link rel="stylesheet" type="text/css" href="../demo.css">
	<script type="text/javascript" src="../../jquery.min.js"></script>
	<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
<style>
	.datagrid-header .datagrid-cell span {
	    font-weight: bold;
	}
	.floatToolX{display: block;top:0;position: absolute;width:2px;height:100%;overflow: hidden;background-color:#5DAC5D;}
	.floatToolY{display: block;left:0;position: absolute;height:1px;width:100%;overflow: hidden;background-color:#5DAC5D;}
	.datagrid-header-row td{
		position: relative;white-space: nowrap;
	}
</style>
<script>
$(function() {
	$.messager.alert('系统提示','<b style="font-size:14px;">有问题欢迎发送问题至邮箱64519473@qq.com!</b>','error');
	var grid_menu = null;
	var grid_win = null;
	var grid_event = null;
	$.extend($.fn.datagrid.methods, { 
		//标题拖拽
		columnConfig: function(jq){
			return jq.each(function(){
				if(grid_menu==null) grid_menu = $('<div style="width:100px;display:none;"><div data-options="iconCls:\'icon-config-hide\'">隐藏该列</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-all\'">配置所有列</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-excel\'">导出Excel</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-save\'">保存配置</div><div class="menu-sep"></div><div data-options="iconCls:\'icon-config-refresh\'">恢复默认</div></div>').appendTo('body');
				var target = this;//target 就是$("#gridTables")
				var initColumns = [];//默认列属性
				var _cs = $(target).datagrid('options').columns[0]; 
				for(var i=0;i<_cs.length;i++){
					var _c = {};
					var _p = _cs[i];
					for(var _o in _p){
						_c[_o] = _p[_o];
					}
					initColumns.push(_c);
				}
				target.columnConfigTag = true;
				var panel = $(this).datagrid('getPanel');
				panel.attr("id",target.id);
				var cells = panel.find('div.datagrid-header td[field]');
				var divBody = panel.find("div.datagrid-body:last").css("overflow-x","auto");
				var scrollInterv = false;//拖拽滚动计时器
				var dragLocation = {x:0,y:0};//当前鼠标位置
				var dragStyle="";//拖拽原始位置Style
				function bodyDragingX(e){
					//拖拽至最左侧,右侧,横向滚动条跟随自动滚动
					if (dragLocation.x > divBody.width() + divBody.offset().left - 100) {
	                    if (!scrollInterv)
	                    	//向右滚动
	                        scrollInterv = window.setInterval(function () { divBody.scrollLeft(divBody.scrollLeft() + 3); }, 10);
	                } else if (dragLocation.x < divBody.offset().left + 100) {
	                    if (!scrollInterv)
	                    	//向左滚动
	                        scrollInterv = window.setInterval(function () { divBody.scrollLeft(divBody.scrollLeft() - 3); }, 10);
	                } else {
	                	if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
	                }
				}
				var grid_win_panel_show;
				var grid_win_panel_hide;
				function bodyDragingY(e){
					//拖拽至最左侧,右侧,横向滚动条跟随自动滚动
					var grid_win_panel = dragLocation.x < grid_win_panel_hide.offset().left - 33 ? grid_win_panel_show : grid_win_panel_hide;
					if (dragLocation.y > grid_win_panel.height() + grid_win_panel.offset().top - 20) {
	                    if (!scrollInterv)
	                    	//向右滚动
	                        scrollInterv = window.setInterval(function () { grid_win_panel.scrollTop(grid_win_panel.scrollTop() + 3); }, 10);
	                } else if (dragLocation.y < grid_win_panel.offset().top + 20) {
	                    if (!scrollInterv)
	                    	//向左滚动
	                        scrollInterv = window.setInterval(function () { grid_win_panel.scrollTop(grid_win_panel.scrollTop() - 3); }, 10);
	                } else {
	                	if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
	                }
				}
				function bodyDragingOver(){
					if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
				}
				cells.each(function(){
					//checkbox不允许拖拽
					//if($(this).find(":checkbox:first").length==1)
					//	return;
					var tdHeader = $(this);
					tdHeader.attr("_drop","1").draggable({
						revert:true,
						delay:100,
						cursor:'pointer',
						edge:5,
						proxy:function(source){
							var p = $('<div style="position:absolute;border:2px dashed #999999;background-color: #efefef;color:#FF5500;"/>').appendTo('body');
							p.html($(source).html());
							p.css({width:p.width()+"px",height:p.height()+"px","overflow":"hidden"});
							p.hide();
							return p;
						},
						onBeforeDrag:function(e){
							if(e.button!=0)return false;//如果不是左键不执行
							e.data.startLeft = $(this).offset().left;
							e.data.startTop = $(this).offset().top;
						},
						onStartDrag: function(e){
							$(document).bind("mousemove", bodyDragingX).bind("mouseup",bodyDragingOver);
							dragLocation = {x:0,y:0};
							dragStyle = $(this).attr("style");
							if(typeof(dragStyle)=="undefined")dragStyle="";
							$(this).draggable('proxy').css({
								left:-10000,
								top:-10000
							});
						},
						onStopDrag: function(e){
							$(document).unbind("mousemove", bodyDragingX).unbind("mouseup",bodyDragingOver);
						},
						onDrag:function(e){
							dragLocation = {x:e.pageX,y:e.pageY};
							$(this).draggable('proxy').show().css({
								left:e.pageX+15,
								top:e.pageY+15
							});
							return false;
						}
					}).droppable({
						accept:'#'+target.id+' td[_drop]',//本grid拖拽
						onDragOver:function(e,source){
							$(source).draggable('proxy').css("color","#078A08");
							var span = $(this).find(".floatToolX");
							if(span.length==0){
								var height = $(this).height();
                                $(this).append('<span class="floatToolX" width="' + $(this).width() + '" height="' + height + '" style="height:' + height + 'px";left:0/>');
                                span = $(this).find(".floatToolX");
							}
							var left = $(this).offset().left;
							var width = $(this).width()/2;
							if(dragLocation.x > left + width){
								//右侧
								span.attr("style","height:"+span.attr("height")+"px;right:0");
							}else{
								//左侧
								span.attr("style","height:"+span.attr("height")+"px;left:0");
							}
						},
						onDragLeave:function(e,source){
							$(source).draggable('proxy').css("color","#FF5500");
							$(this).find(".floatToolX").remove();
						},
						onDrop:function(e,source){
							var targetTd = $(this);
							var span = targetTd.find(".floatToolX:first");
							if(span.length>0){
								span=span.first();
								var fromField = $(source).attr('field');
								var toField = targetTd.attr('field');
								setTimeout(function(){
									var left = span.attr("style").indexOf("left")!=-1;
									moveField(fromField,toField,left);
									//方案1本地数据加载
									span.remove();
									if(left)
										$(source).attr("style",dragStyle).insertBefore(targetTd);
									else
										$(source).attr("style",dragStyle).insertAfter(targetTd);
									$(target).datagrid("loadData",$(target).datagrid("getData"));
									//方案2重新请求数据加载$(target).datagrid();$(target).datagrid("columnConfig");
								},0);
								$('#grid_float_div').remove();
							}
						}
					}).contextmenu(function(e){
						e.preventDefault();
						grid_event = target;
						grid_menu.menu({
							onClick : function(item) {
								if(item.text=="隐藏该列"){
									var columns = $(target).datagrid('options').columns[0];
									var existsShow = false;
									var field = tdHeader.attr('field');
									for(var i=0; i<columns.length; i++){
										var column = columns[i]; 
										if (!column.hidden && column.field != field){
											existsShow = true;
											break;
										}
									}
									if(existsShow)
										$(target).datagrid('hideColumn', field);
									else{
										$.messager.alert('系统提示','<b style="font-size:14px;">该列无法隐藏，至少得保证有一列显示!</b>','error');
									}
								}else if(item.text=="配置所有列"){
									var columns = $(target).datagrid('options').columns[0];
									if(grid_win==null){
										$('body').append('<div id="grid_win"><div class="easyui-layout" data-options="fit:true"><div data-options="region:\'west\',border:false,collapsible:false" style="width:210px;border:false;overflow-x:hidden" title="显示列" id="grid_win_panel_show"></div><div data-options="region:\'center\'" style="border-top:none;border-bottom:none;text-align:center;" id="grid_win_center"><a href="javascript:void(0)" id="grid_win_all_hide" title="全部隐藏" style="width:80%" data-options="iconCls:\'layout-button-right\'"></a><br/><a href="javascript:void(0)" id="grid_win_all_show" style="width:80%;margin-top:15px;" title="全部显示" data-options="iconCls:\'layout-button-left\'"></a></div><div data-options="region:\'east\',border:false,collapsible:false" style="width:210px;overflow-x:hidden" title="隐藏列" id="grid_win_panel_hide"></div><div data-options="region:\'south\'" style="text-align:center;padding:5px;height:40px;border-bottom:none;border-left:none;border-right:none;"><a class="easyui-linkbutton" data-options="iconCls:\'icon-ok\'" href="javascript:void(0)" id="grid_win_save">保存</a><a class="easyui-linkbutton" data-options="iconCls:\'icon-cancel\'" href="javascript:void(0)" style="margin-left:15px;" id="grid_win_cancel">取消</a></div></div></div>');
										$('#grid_win').children().layout();
										$('#grid_win_all_hide,#grid_win_all_show,#grid_win_save,#grid_win_cancel').linkbutton({onClick:function(e){
											if(this.id=='grid_win_all_hide'){
												$('#grid_win_panel_show div[itemField]').appendTo($('#grid_win_panel_hide'));
											}else if(this.id=='grid_win_all_show'){
												$('#grid_win_panel_hide div[itemField]').appendTo($('#grid_win_panel_show'));
											}else if(this.id=='grid_win_save'){
												//保存配置
												cells = panel.find('div.datagrid-header td[field]');
												columns = $(target).datagrid('options').columns[0];
												var newColumns = [];
												var tempDiv = $("<div></div");
												var headTr = cells.first().parent();
												$('#grid_win_panel_show div[itemField]').each(function(){
													var field = $(this).attr("itemField");
													for(var i=0;i<columns.length;i++){
														var c = columns[i];
														if(c.field==field){
															c.hidden = false;
															newColumns.push(c);
															cells.filter('[field="'+field+'"]:first').show().appendTo(tempDiv);//方案1
														}
													}
												});
												if(newColumns.length==0){
													$.messager.alert('系统提示','<b style="font-size:14px;">无法保存，至少得保证有一列显示!</b>','error');
													return;
												}
												$('#grid_win_panel_hide div[itemField]').each(function(){
													var field = $(this).attr("itemField");
													for(var i=0;i<columns.length;i++){
														var c = columns[i];
														if(c.field==field){
															c.hidden = true;
															newColumns.push(c);
															cells.filter('[field="'+field+'"]:first').hide().appendTo(tempDiv);//方案1
														}
													}
												});
												grid_win.window('close');
												$(target).datagrid('options').columns[0] = newColumns;
												//方案1本地数据加载
												headTr.append(tempDiv.children());
												$(target).datagrid("loadData",$(target).datagrid("getData"));
												//方案2重新请求数据加载$(target).datagrid();$(target).datagrid("columnConfig");
											}else if(this.id=='grid_win_cancel'){
												grid_win.window('close');
											}
										}});
									}
									grid_win_panel_show = $('#grid_win_panel_show');
									grid_win_panel_hide = $('#grid_win_panel_hide');
									if(grid_win==null){
										grid_win_panel_show.add(grid_win_panel_hide).contextmenu(function(e){
											e.preventDefault();
										});
									}
									var height = $(window).height()-100;
									if(height<250) height = 250;
									var borderColor = "";
									borderColor = $('#grid_win_center').css("padding-top",(height/2-70)+"px").css("border-left-color");
									var display="";
									var hidden="";
									for(var i=0;i<columns.length;i++){
										var column = columns[i];
										var row = column.checkbox ? '<input type="checkbox"/>' : column.title;
										if(column.hidden){
											hidden+='<div style="position: relative;height:16px;padding:3px;width:204px;white-space: nowrap;overflow:hidden;border-bottom:1px dashed '+borderColor+'" itemField="'+column.field+'">'+row+'</div>';
										}else{
											display+='<div style="position: relative;height:16px;padding:3px;width:204px;white-space: nowrap;overflow:hidden;border-bottom:1px dashed '+borderColor+'" itemField="'+column.field+'">'+row+'</div>';
										}
									}
									var divs = grid_win_panel_show.html(display).find("div");
									divs = divs.add(grid_win_panel_hide.html(hidden).find("div"));
									divs.draggable({
										revert:true,
										delay:100,
										cursor:'pointer',
										edge:5,
										proxy:function(source){
											var p = $('<div id="grid_float_div" style="z-index:99999;padding:5px;position:absolute;border:2px dashed #999999;background-color: #efefef;color:#FF5500;"/>').appendTo('body');
											p.html($(source).html());
											p.css({width:p.width()+"px",height:p.height()+"px","overflow":"hidden"});
											p.hide();
											return p;
										},
										onBeforeDrag:function(e){
											if(e.button!=0)return false;//如果不是左键不执行
											e.data.startLeft = $(this).offset().left;
											e.data.startTop = $(this).offset().top;
										},
										onStartDrag: function(e){
											$(document).bind("mousemove", bodyDragingY).bind("mouseup",bodyDragingOver);
											dragLocation = {x:0,y:0};
											dragStyle = $(this).attr("style");
											if(typeof(dragStyle)=="undefined")dragStyle="";
											$(this).draggable('proxy').css({
												left:-10000,
												top:-10000
											});
										},
										onStopDrag: function(e){
											$(document).unbind("mousemove", bodyDragingY).unbind("mouseup",bodyDragingOver);
										},
										onDrag:function(e){
											dragLocation = {x:e.pageX,y:e.pageY};
											$(this).draggable('proxy').show().css({
												left:e.pageX+15,
												top:e.pageY+15
											});
											return false;
										}
									}).droppable({
										accept:'div[itemField]',
										onDragOver:function(e,source){
											$(source).draggable('proxy').css("color","#078A08");
											var span = $(this).find(".floatToolY");
											if(span.length==0){
												var height = $(this).height();
                                                $(this).append('<span class="floatToolY" width="' + $(this).width() + '" height="' + height + '" style="margin-left:3px;height:' + height + 'px";left:0/>');
                                                span = $(this).find(".floatToolY");
											}
											var top = $(this).offset().top;
											var height = $(this).height()/2;
											if(dragLocation.y > top + height){
												//下侧
												span.attr("style","margin-left:3px;width:"+span.attr("width")+"px;bottom:0");
											}else{
												//上侧
												span.attr("style","margin-left:3px;width:"+span.attr("width")+"px;top:0");
											}
										},
										onDragLeave:function(e,source){
											$(source).draggable('proxy').css("color","#FF5500");
											$(this).find(".floatToolY").remove();
										},
										onDrop:function(e,source){
											if(scrollInterv){window.clearInterval(scrollInterv);scrollInterv = false;}
											var targetItem = $(this);
											var span = targetItem.find(".floatToolY:first");
											if(span.length>0){
												span=span.first();
												setTimeout(function(){
													var top = span.attr("style").indexOf("top")!=-1;
													span.remove();
													if(top)
														$(source).attr("style",dragStyle).insertBefore(targetItem);
													else
														$(source).attr("style",dragStyle).insertAfter(targetItem);
												},0);
											}
											$('#grid_float_div').remove();
										}
									}).contextmenu(function(e){
										e.preventDefault();
										var targetPanel = $(this).parents('div[id]:first');
										$(this).appendTo($('#'+(targetPanel.attr('id')=='grid_win_panel_show' ? 'grid_win_panel_hide' : 'grid_win_panel_show')));
									});
									grid_win = $('#grid_win').window({
										title:'配置所有列',
									    width:500,
									    height:height,
									    collapsible:false,
									    minimizable:false,
									    maximizable:false,
									    modal:true
									}).window('hcenter');  
								}else if(item.text=="导出Excel"){
									$.messager.alert('系统提示','<b style="font-size:14px;">该功能近期上线,敬请期待...</b>');
								}else if(item.text=="保存配置"){
									$.messager.alert('系统提示','<b style="font-size:14px;">该列无法隐藏，至少得保证有一列显示!</b>','error');
								}else if(item.text=="恢复默认"){
									$.messager.confirm('系统提示', '您确认清除该列表所有列配置信息?<br/><span style="color:red;">(点击确定自动删除列表配置)</span>', function(r){
										if (r){
											$(target).datagrid('options').columns[0] = initColumns;
											$(target).datagrid();
											$(target).datagrid('columnConfig');
											/*$.ajax({
												type:"POST",                         
												url: request_path+"columnClean.do",               
												data: {pageId:grid.getGridParam("pageId")+"_"+grid.attr("id")},  
												success: function(msg){
													if(msg==-1){
														alert("清除失败,服务器异常,请稍后重新或联系管理员!");
													}else if(msg==-2){
														alert("清除失败,登录时间过长,请重新登录!");
													}else{
														alert("配置清除成功!");
														window.location.reload();
													}
												}
											});*/
										}
									});
								}
							}
						}).menu('show', {
							left : e.pageX,
							top : e.pageY
						});
					});
                });
                // move field to another location
				function moveField(from,to,left){
					var columns = $(target).datagrid('options').columns;
					var cc = columns[0];
					var c = _remove(from);
					if (c){
						_insert(to,c,left);
					}
					function _remove(field){
						for(var i=0; i<cc.length; i++){
							if (cc[i].field == field){
								var c = cc[i];
								cc.splice(i,1);
								return c;
							}
						}
						return null;
					}
					function _insert(field,c,left){
						var newcc = [];
						for(var i=0; i<cc.length; i++){
							if (cc[i].field == field){
								if(left){
									newcc.push(c);
									newcc.push(cc[i]);
								}else{
									newcc.push(cc[i]);
									newcc.push(c);
								}
							}else
								newcc.push(cc[i]);
						}
						columns[0] = newcc;
					}
				}
			});
		}
	}); 
	var cols = [{ field: 'productid',checkbox:true, title: '测试名1测试名1测试名1测试名1测试名1', align: 'center',width:120 },
	            { field: 'productname', title: '测试值2测试值2测试值2测试值2测试值2测试值2测试值2', align: 'center', width: 250},
	            { field: 'unitcost', title: '测试值3', align: 'center', width: 250},
	            { field: 'status', title: '测试值4', align: 'center', width: 250},
	            { field: 'listprice', title: '测试值5', align: 'center', width: 250},
	            { field: 'attr1', title: '测试值6', align: 'center', width: 250},
	            { field: 'itemid', title: '测试值7', align: 'center', width: 250}];
    var url="datagrid_data1.json";
	$("#grid").datagrid({
        url: url,
        type: "post",
        datatype: "json",
        fit:true,
        //height:200,
        loadMsg: "数据加载中，请稍后...",
        rownumbers: true,
        pagination: true,
        singleSelect: true,
        columns: [cols],
        pageSize:20,
        pageList: [10, 20, 30], 
        //bind数据成功重新设置拖动对象
        onLoadSuccess: function (data) {          
            //drag();
        }
    }).datagrid("columnConfig");
});
</script>
</head>
<body>
<table id="grid"></table>
<table id="grid1"></table>
</body>
<!-- END BODY -->
</html>